#include <iostream>
#include <new>

/*
new malloc
delete free

1.
malloc 和 free是c的库函数
new和delete 称作运算符

2.
malloc分配内存失败，返回的是空指针
new 分配内存失败，返回bad_alloc异常

3.
malloc按照字节分配内存，需手动计算需要的字节数，返回类型为void*，需要进行强转，只负责开辟内存，而不负责初始化
new按照类型分配内存，自动计算所需的字节数，返回类型为T*，无需强转，也负责内存初始化操作（调用构造函数）

4.
free 只负责释放内存
delete 还负责析构
delete[]和new[]搭配使用


扩展：
new有多少种？
1. 常规new
int *p = new int(42);

2. nothrow new
int *p = new (nothrow) int(42);

3. const new
const int *p = new const int(42);

4. placement new
int data = 0;
int *p = new (&data) int(42);
*/
int main() {
  int *p = (int *)malloc(sizeof(int));
  if (p == nullptr) {
    std::cout << "failed to allocate memory!" << std::endl;
    return -1;
  }
  *p = 42;
  free(p);

  try {
    int *p2 = new int(42);
    delete p2;
  } catch (const std::bad_alloc &e) {
  }

  int *q = (int *)malloc(sizeof(int) * 20);
  if (q == nullptr) {
    std::cout << "failed to allocate memory!" << std::endl;
    return -1;
  }
  free(q);

  int *q1 = new int[4];   // 不进行初始化
  int *q2 = new int[4](); // 初始化为0
  for (int i = 0; i < 4; i++) {
    std::cout << q1[i] << " "; // -842150451 -842150451 -842150451 -842150451
  }
  std::cout << std::endl;
  for (int i = 0; i < 4; i++) {
    std::cout << q2[i] << " "; // 0 0 0 0
  }
  std::cout << std::endl;

  return 0;
}